"""聊天界面组件"""

import streamlit as st
import time
from typing import Dict, List


def display_message(message: Dict) -> None:
    """显示消息"""
    role = message.get("role", "user")
    content = message.get("content", "")
    deep_research = message.get("deep_research", False)
    timestamp = message.get("timestamp", time.time())
    
    # 时间格式化
    time_str = time.strftime("%H:%M", time.localtime(timestamp))
    
    if role == "user":
        st.markdown(f"""
        <div class="user-message">
            <div class="message-header">
                <strong>👤 您</strong>
                <span class="timestamp">{time_str}</span>
            </div>
            <div class="message-content">{content}</div>
        </div>
        """, unsafe_allow_html=True)
    else:
        # 助手消息
        research_badge = '<span class="deep-research">🔍 深度研究</span>' if deep_research else ''
        
        st.markdown(f"""
        <div class="assistant-message">
            <div class="message-header">
                <strong>🤖 Cairo助手</strong>
                {research_badge}
                <span class="timestamp">{time_str}</span>
            </div>
            <div class="message-content">{format_code_blocks(content)}</div>
        </div>
        """, unsafe_allow_html=True)


def format_code_blocks(text: str) -> str:
    """格式化代码块"""
    import re
    
    # 检测代码块
    code_pattern = r'```(\w+)?\n?(.*?)```'
    
    def replace_code(match):
        language = match.group(1) or 'cairo'
        code = match.group(2)
        return f'<div class="code-block"><pre><code class="language-{language}">{code}</code></pre></div>'
    
    # 替换代码块
    formatted_text = re.sub(code_pattern, replace_code, text, flags=re.DOTALL)
    
    return formatted_text


def render_chat_input() -> tuple[str, bool, bool]:
    """渲染聊天输入界面"""
    col1, col2 = st.columns([4, 1])
    
    with col1:
        user_input = st.text_area(
            "💬 请输入您关于Cairo的问题...",
            height=100,
            placeholder="例如: Cairo中的felt252类型有什么特点？",
            disabled=st.session_state.get("is_loading", False)
        )
    
    with col2:
        st.write("")  # 空行
        st.write("")  # 空行
        
        # 发送按钮
        send_button = st.button("📤 发送", type="primary", disabled=st.session_state.get("is_loading", False))
        
        # 深度研究按钮
        deep_research_button = st.button(
            "🔍 深度研究", 
            type="secondary", 
            disabled=st.session_state.get("is_loading", False),
            help="获得更详细的分析报告"
        )
    
    return user_input, send_button, deep_research_button


def render_sidebar() -> None:
    """渲染侧边栏"""
    with st.sidebar:
        st.header("⚙️ 设置")
        
        # 模型信息
        st.info("""
        **当前配置:**
        - 模型: 千问3 (qwen-plus)
        - 模式: 流式对话
        - 支持: 深度研究
        """)
        
        # API连接测试
        if st.button("🔗 测试API连接"):
            try:
                import requests
                from config.settings import config
                response = requests.get(f"http://localhost:{config.api.port}/api/health", timeout=5)
                if response.status_code == 200:
                    st.success("✅ API连接正常")
                else:
                    st.error(f"❌ API错误: {response.status_code}")
            except Exception as e:
                st.error(f"❌ 连接失败: {str(e)}")
        
        # 功能说明
        st.markdown("""
        **功能特性:**
        - ✅ Cairo语法解析
        - ✅ 代码错误诊断
        - ✅ 最佳实践建议
        - ✅ 深度研究分析
        - ✅ 代码高亮显示
        """)
        
        # 清空对话
        if st.button("🗑️ 清空对话", type="secondary"):
            st.session_state.messages = []
            st.rerun()
